const net = require('net')
const MyTransformCode = require('./MyTransformCode')

const trans = new MyTransformCode()
const server = net.createServer()
let packContent = null

server.listen(1234, 'localhost')

server.on('listening', () => {
  console.log('服务端运行在 localhost:1234')
})

server.on('connection', (socket) => {
  // socket 类似双工流。可读可写
  socket.on('data', (chunk) => {
    if(packContent) {
      chunk = Buffer.concat([packContent, chunk])
    }
    let packlen = 0
    while(packlen = trans.getPackageLen(chunk)) {
      // 包内有内容
      const currentChunk = chunk.slice(0, packlen)
      chunk = chunk.slice(packlen)
      const data = trans.decode(currentChunk)
      console.log(data.body)
      socket.write(trans.encode(data.body, data.seriesNum))
    }
    packContent = packContent ? Buffer.concat([packContent, chunk]) : chunk
  })
})
